package cloud.mbase.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;

public class TokenUtil {
    public static String genereteToken(final Authentication auth){
        return Jwts.builder()
                .setSubject(((User) auth.getPrincipal()).getUsername())
                .setExpiration(StringUtil.authOutDate())
                .signWith(SignatureAlgorithm.HS512, StringUtil.SECRET)
                .compact();
    }
    public static Boolean validateToken(final String token, final UserDetails userDetails) {
        final String username = getUsernameFromToken(token);
        final boolean isExpired = isExpiredDateFromToken(token);
        return (username.equals(userDetails.getUsername()) && !isExpired);
    }

    public static String getUsernameFromToken(final String token) {
        return Jwts.parser()
                .setSigningKey(StringUtil.SECRET)
                .parseClaimsJws(token.replace(StringUtil.BEARER, ""))
                .getBody()
                .getSubject();
    }

    private static boolean isExpiredDateFromToken(String token) {
        Date expireDate = Jwts.parser()
                .setSigningKey(StringUtil.SECRET)
                .parseClaimsJws(token.replace(StringUtil.BEARER, ""))
                .getBody()
                .getExpiration();
        if (expireDate.getTime() > System.currentTimeMillis()) {
            return false;
        }
        return true;
    }
}
